package com.duoec.magichour.core.web.freemarker.pipe.common;

import com.duoec.magichour.core.web.freemarker.pipe.Pipe;
import com.google.common.base.Strings;
import freemarker.core.BasePipe;
import freemarker.core.Environment;
import freemarker.template.*;

import java.util.List;

/**
 * thumb2使用先裁剪再压缩的方式,如果需要使用直接压缩,请使用thumb
 */
@Pipe("thumb2")
public class Thumb2Pipe extends BasePipe {
    @Override
    protected TemplateModel render(Environment env) throws TemplateException {
        final String imagePath = this.getString(env);

        return (TemplateMethodModelEx) arguments -> {
            SimpleNumber wSimpleScalar = (SimpleNumber) arguments.get(0);
            SimpleNumber hSimpleScalar = (SimpleNumber) arguments.get(1);
            String targetImagePath = imagePath;
            targetImagePath = getImageThumb(imagePath, wSimpleScalar.getAsNumber().intValue(), hSimpleScalar.getAsNumber().intValue());

            return new SimpleScalar(targetImagePath);
        };
    }

    private class BIMethod implements TemplateMethodModelEx {
        private String s;

        private BIMethod(String s) {
            this.s = s;
        }

        public Object exec(List args) throws TemplateModelException {
            checkMethodArgCount(args, 1);
            return s.startsWith(getStringMethodArg(args, 0)) ?
                    TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
        }
    }

    public String getImageThumb(String imageUrl, int thumbWidth, int thumbHeight) {
        String url = imageUrl;
        if (Strings.isNullOrEmpty(url))
            return url;
        if (url.startsWith("http")) {
            //试着裁剪图片.
            if (
                    url.startsWith("http://7xrxy0.com2.z0.glb.qiniucdn.com/") ||
                            url.startsWith("http://fsxf.fangdd.com/") ||
                            url.startsWith("https://fsxf.fangdd.com/") ||
                            url.startsWith("http://fs.esf.fangdd.com") ||
                            url.startsWith("https://fs.esf.fangdd.com")
                    ) {
                //七牛图片服务器
                // 文档:http://developer.qiniu.com/code/v6/api/kodo-api/image/imagemogr2.html#imagemogr2-thumbnail-spec
                int index = url.indexOf("?");
                if (index > -1) {
                    url = url.substring(0, index);
                }
                url += "?imageMogr2/thumbnail/!" + thumbWidth + "x" + thumbHeight + "r|imageView2/1/w/" + thumbWidth + "/h/" + thumbHeight;
            }
        }
        return url;
    }
}
